import {getRequest} from "./api";
import CryptoJS from "crypto-js";

export const initMenu = (router, store) => {
    if (store.state.routes.length > 0) {
        return;
    }

    // 调后端接口获取菜单(此接口可以是真实接口，也可以是虚无接口，因为菜单信息已在登录时返回了)
    // getRequest("/sysMenu/getMenusByUserId").then(data => {
    getRequest("/sysMenu/faker").then(resp => {
        if (resp) {
            let menus = JSON.parse(window.localStorage.getItem("user")).menus;
            let fmtRoutes = formatRoutes(menus);
            router.addRoutes(fmtRoutes);
            store.commit('initRoutes', fmtRoutes);
            store.dispatch('connect');
        }
    });
}

export const formatRoutes = (routes) => {
    let fmRoutes = [];
    routes.forEach(router => {
        let {
            path,
            component,
            name,
            meta,
            iconCls,
            children
        } = router;
        if (children && children instanceof Array) {
            children = formatRoutes(children);
        }
        let fmRouter = {
            path: path,
            name: name,
            iconCls: iconCls,
            meta: meta,
            children: children,
            component(resolve) {
                if (component.startsWith("Home")) {
                    require(['../views/' + component + '.vue'], resolve);
                } else if (component.startsWith("Swagger") || component === "AppManage" || component === "InterfaceManage" || component === "InterfaceTestRecord") {
                    require(['../views/swagger/' + component + '.vue'], resolve);
                }

                // else {
                //     require(['../views/Login.vue'], resolve);
                // }
            }
        }
        fmRoutes.push(fmRouter);
    })
    return fmRoutes;
}